package edu.hawaii.teams.halealohacli.command;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Sets a base line of energy consumed for a 
 * certain tower based on the date. Default
 * date is yesterday.
 * 
 * @author Hansen Cheng
 *
 */
public class SetBaseLine implements Command {
  
  
  /**
   * Iterates through the source to retrieve energy data
   * in a 24 hour period.
   * 
   * @param client - a WattDepotClient.
   * @param details - an array with the inputs from command prompt by user.
   * @return buffer - a string of 24 values representing the energy in 24 hours
   * @throws Exception - error.
   * 
   */
  public String getData(WattDepotClient client, String... details) throws Exception {
    
    
    String currentTower = null;
    String date = null;
    StringBuilder buffer = new StringBuilder();
    
    for (String text : details) {
      try {
        if (currentTower == null) {
          currentTower = text;
          buffer.append(currentTower + " ");
        }
        else if (date == null) {
          date = text;
        }
        
        if (currentTower != null && date != null) {
          Date today = new Date();
          Date day = new SimpleDateFormat("yyyy-MM-dd", Locale.US).parse(date);
          
          if (today.getTime() == day.getTime() || day.getTime() > today.getTime()) {
            return "Sorry date is too current to set the baseline. Try an earlier date.";
          }
          else {
            XMLGregorianCalendar start = Tstamp.makeTimestamp(day.getTime());
            start.setTime(0, 0, 0);
            
            XMLGregorianCalendar end = start;
            end.setTime(0, 0, 0);
            
            //Iterate through the tower to get 24 hours
            //of values (energy consumed)
            for (int hour = 0; hour < 24; hour++) {
              end = Tstamp.incrementHours(start, 1);
              double energy = client.getEnergyConsumed(currentTower, start, end, 60);
              //Create a string of 24 values. It will be splitted and add to array
              //in Processor class
              buffer.append(Double.toString(energy) + " ");
              start = Tstamp.incrementHours(start, 1);
              
            }
            
            currentTower = null;
            date = null;
          }
        } //end of if statement that tests if variables to contain input is not empty
      }
      catch (ResourceNotFoundException re) {
        buffer.append("Error: The source " + currentTower + " could not be found.\n\n");
      }
    }

    return buffer.toString();
  }

}
